package com.example.mvvm.http;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpClient {

    private String url = "http://shejiao.broyoung.com";
    //private String url = "https://www.wanandroid.com/";
    private static HttpClient instance = null;
    private OkHttpClient client;
    private RetrofitApi retrofitApi;

    public static HttpClient getInstance() {
        if (instance == null) {
            synchronized (HttpClient.class) {
                if (instance == null) {
                    instance = new HttpClient();
                }
            }
        }
        return instance;
    }

    private HttpClient() {
        initHttp();
        initRetrofit();
    }

    public static RetrofitApi getApi() {
        if (instance == null) {
            instance = getInstance();
        }
        return instance.retrofitApi;
    }

    private void initRetrofit() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .client(client)
                .build();
        retrofitApi = retrofit.create(RetrofitApi.class);
    }

    private void initHttp() {
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .followRedirects(true)
                .build();
    }
}
